package com.microframework.boot.fs.service.impl;

import java.io.IOException;

import org.apache.commons.io.FilenameUtils;
import org.springframework.core.io.InputStreamResource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import com.microframework.boot.fs.service.IMinioService;

import io.minio.BucketExistsArgs;
import io.minio.GetObjectArgs;
import io.minio.GetObjectResponse;
import io.minio.MakeBucketArgs;
import io.minio.MinioClient;
import io.minio.PutObjectArgs;
import io.minio.RemoveObjectArgs;
import io.minio.errors.MinioException;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;

@Service
@Slf4j
@RequiredArgsConstructor
public class MinioServiceImpl implements IMinioService {
	private final MinioClient minioClient;

	// 创建存储桶（如果不存在）
	@Override
	public void createBucketIfMissing(String bucketName) throws Exception {
		boolean found = minioClient.bucketExists(BucketExistsArgs.builder().bucket(bucketName).build());
		if (!found) {
			minioClient.makeBucket(MakeBucketArgs.builder().bucket(bucketName).build());
		}
	}

	// 上传文件
	@Override
	public String uploadFile(String bucketName, MultipartFile file, String objectName) throws Exception {
		createBucketIfMissing(bucketName);
		minioClient.putObject(PutObjectArgs.builder().bucket(bucketName).object(objectName)
				.stream(file.getInputStream(), file.getSize(), -1).contentType(file.getContentType()).build());
		return objectName;
	}

	// 下载文件
	@Override
	public GetObjectResponse downloadFile(String bucketName, String objectName) throws Exception {
		return minioClient.getObject(GetObjectArgs.builder().bucket(bucketName).object(objectName).build());
	}

	// 删除文件
	@Override
	public void deleteFile(String bucketName, String objectName) throws Exception {
		minioClient.removeObject(RemoveObjectArgs.builder().bucket(bucketName).object(objectName).build());
	}

	@Override
	public ResponseEntity<InputStreamResource> getThumbnail(String bucketName,String thumbnail) {
		try {
			
			String filenameWithoutExtension = FilenameUtils.removeExtension(thumbnail);
            // 1. 从MinIO获取文件
            GetObjectResponse response = downloadFile(bucketName, filenameWithoutExtension);
            // 2. 根据文件扩展名确定内容类型
            MediaType mediaType = determineMediaType(thumbnail);
            // 3. 构建响应 - 使用inline让浏览器直接显示
            return ResponseEntity.ok()
                    .contentType(mediaType)
                    .header(HttpHeaders.CONTENT_DISPOSITION, "inline; filename=\"" + thumbnail + "\"")
                    .body(new InputStreamResource(response));
            
        } catch (MinioException e) {
            // MinIO特定异常处理
            return ResponseEntity.status(404).body(null);
        } catch (IOException e) {
            // IO异常处理
            return ResponseEntity.status(500).body(null);
        } catch (Exception e) {
            // 其他异常处理
            return ResponseEntity.status(500).body(null);
        }
	}
	
	@Override
	public MediaType determineMediaType(String filename) {
        String extension = filename.substring(filename.lastIndexOf(".") + 1).toLowerCase();
        return switch (extension) {
            case "jpg", "jpeg" -> MediaType.IMAGE_JPEG;
            case "png" -> MediaType.IMAGE_PNG;
            case "gif" -> MediaType.IMAGE_GIF;
            case "webp" -> MediaType.parseMediaType("image/webp");
            default -> MediaType.APPLICATION_OCTET_STREAM;
        };
    }

	@Override
	public String getFileExtension(MultipartFile file) {
	    if (file == null || file.isEmpty()) {
	        return ""; // 或者抛出异常
	    }
	    
	    // 获取原始文件名
	    String originalFilename = file.getOriginalFilename();
	    
	    // 处理空文件名的情况
	    if (originalFilename == null || originalFilename.isEmpty()) {
	        return "";
	    }
	    
	    // 查找最后一个点号的位置
	    int lastDotIndex = originalFilename.lastIndexOf('.');
	    
	    // 处理没有扩展名或隐藏文件的情况
	    if (lastDotIndex < 0) {
	        return ""; // 没有扩展名
	    }
	    
	    // 提取扩展名并转换为小写
	    return originalFilename.substring(lastDotIndex + 1).toLowerCase();
	}

}
